package com.siashan.unipay4j.wx.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.siashan.unipay4j.core.IPayConfig;
import com.siashan.unipay4j.core.Result;
import com.siashan.unipay4j.core.UnipayConst;
import com.siashan.unipay4j.core.pay.IClose;
import com.siashan.unipay4j.core.util.EnumUtil;
import com.siashan.unipay4j.wx.AbstractWxPay;
import com.siashan.unipay4j.wx.WxPayVersionEnum;
import com.siashan.unipay4j.wx.model.CloseOrderModel;
import com.siashan.unipay4j.wx.sdk.WXPayConstants;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

import static org.apache.http.HttpStatus.SC_NO_CONTENT;

/**
 *以下情况需要调用关单接口：商户订单支付失败需要生成新单号重新发起支付，要对原订单号调用关单，避免重复支付；
 * 系统下单后，用户支付超时，系统退出不再受理，避免用户继续，请调用关单接口。
 *
 * 注意：订单生成后不能马上调用关单接口，最短调用时间间隔为5分钟。
 *
 * @author siashan
 * @since v1.0.1
 **/
@Slf4j
public class WxPayClose extends AbstractWxPay implements IClose {

    public WxPayClose() {
    }

    public WxPayClose(IPayConfig payConfig) {
        super(payConfig);
    }

    /**
     * 关闭订单
     *
     * @param outTradeNo  平台支付流水号
     *
     * @return 订单关闭结果
     */
    @Override
    public Result execClose(String outTradeNo) {
        WxPayVersionEnum ver = EnumUtil.getIEnum(WxPayVersionEnum.class, wxPayConfig.getVersion());
        Result result = null;
        switch (ver) {
            case V2:
                result = doCloseV2(outTradeNo);
                break;
            case V3:
                result = doCloseV3(outTradeNo);
                break;
            default:
                break;
        }
        return result;
    }

    /**
     * 关闭订单V2
     *
     * @param outTradeNo  平台支付流水号
     *
     * @return 订单关闭结果
     */
    private Result doCloseV2(String outTradeNo) {
        log.info("WxClose::=>关闭订单请求到达,订单号{}", outTradeNo);
        try {
            Map<String, String> param = new HashMap<>();
            param.put("out_trade_no", outTradeNo);
            Map<String, String> r = initWxPay().closeOrder(param);
            String returnCode = r.get(WXPayConstants.RETURN_CODE);
            if (UnipayConst.SUCCESS.equals(returnCode)) {
                String resultCode = r.get(WXPayConstants.RESULT_CODE);
                if (UnipayConst.SUCCESS.equals(resultCode)) {
                    log.info("WxClose::=>关闭订单请求成功,订单号{}", outTradeNo);
                    return Result.tradeSuccess(r);
                } else {
                    String errCode = r.get(WXPayConstants.ERR_CODE);
                    String errCodeDes = r.get(WXPayConstants.ERR_CODE_DES);
                    log.info("WxClose::=>关闭订单请求失败,订单号{}，错误代码{}，错误原因{}", outTradeNo, errCode, errCodeDes);
                    return Result.tradeFail(errCode, errCodeDes);
                }
            } else {
                String returnMsg = r.get(WXPayConstants.RETURN_MSG);
                log.info("WxClose::=>关闭订单失败,订单号{}，错误代码{}，错误原因{}", outTradeNo, returnCode, returnMsg);
                return Result.returnFail(returnCode, returnMsg);
            }
        } catch (Exception e) {
            log.warn("WxClose::=>关闭订单异常,订单号{}", outTradeNo, e);
        }
        return Result.exception();
    }

    /**
     * 关闭订单V3
     *
     * @param outTradeNo  平台支付流水号
     * @since 2.0.1
     * @return 订单关闭结果
     */
    private Result doCloseV3(String outTradeNo) {
        log.info("WxClose::=>关闭订单请求到达,订单号{}", outTradeNo);
        try {
            WechatPayHttpClientBuilder builder = loadBuilder();
            CloseableHttpClient httpClient = builder.build();
            HttpPost httpPost = initHttpPost(wrapCloseUrl(outTradeNo), JSON.toJSONString(wrapCloseOrderModel()));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == SC_NO_CONTENT ) {
                // 关单成功，无报文返回
                log.info("WxClose::=>关闭订单请求成功,订单号{}", outTradeNo);
                return Result.tradeSuccess();
            } else {
                String body = EntityUtils.toString(response.getEntity());
                JSONObject bodyJson = JSON.parseObject(body);
                String errCode = bodyJson.getString(WXPayConstants.CODE);
                String errCodeDes = bodyJson.getString(WXPayConstants.MESSAGE);
                log.info("WxClose::=>关闭订单请求失败,订单号{}，错误代码{}，错误原因{}", outTradeNo, errCode, errCodeDes);
                return Result.tradeFail(errCode, errCodeDes);
            }
        } catch (Exception e) {
            log.warn("WxClose::=>关闭订单异常,订单号{}", outTradeNo, e);
        }
        return Result.exception();
    }

    private CloseOrderModel wrapCloseOrderModel(){
        CloseOrderModel model = new CloseOrderModel();
        model.setMchid(wxPayConfig.getMchId());
        return model;
    }

    private String wrapCloseUrl(String outTradeNo){
        return WXPayConstants.V3_PAY_URL_CLOSE.replace("{out_trade_no}",outTradeNo.trim());
    }


    public static void main(String[] args) {
        System.out.println(String.format(WXPayConstants.V3_PAY_URL_CLOSE,"12345"));
        System.out.println(WXPayConstants.V3_PAY_URL_CLOSE.replace("{out_trade_no}","123456"));
    }
}
